package com.shinhye.elephantsafe;

import java.lang.reflect.Method;
import java.util.List;

import com.shinhye.elephantsafe.domain.AppInfo;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.text.format.Formatter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

//TODO -3- 界面和功能优化，很多内容要做
public class CleanCacheActivity extends Activity {
//	private final String TAG = "CleanCacheActivity";
	private final int MSG_SCANNING = 0x001;
	private final int MSG_CACHE = 0x002;
	private final int MSG_FINISH = 0x003;
	
	private ProgressBar pb_clean_progress;
	private TextView tv_clean_progress;
	private LinearLayout ll_cachecontainer;
	private PackageManager pm;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what) {
			case MSG_SCANNING:
				tv_clean_progress.setText("正在扫描 " + (String) msg.obj);
				break;
			case MSG_CACHE:
				final AppInfo cache = (AppInfo) msg.obj;
				
				View view = View.inflate(CleanCacheActivity.this, R.layout.item_cache, null);
				ImageView iv_appicon = (ImageView) view.findViewById(R.id.iv_appicon);
				TextView tv_appname = (TextView) view.findViewById(R.id.tv_appname);
				TextView tv_cachesize = (TextView) view.findViewById(R.id.tv_cachesize);
				ImageView iv_trush = (ImageView) view.findViewById(R.id.iv_trush);
				
				iv_appicon.setImageDrawable(cache.getIcon());
				tv_appname.setText(cache.getName());
				tv_cachesize.append(Formatter.formatFileSize(CleanCacheActivity.this, cache.getCachesize()));
				iv_trush.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Method[] methods = PackageManager.class.getMethods();
						for(Method method : methods){
							try {
								if("deleteApplicationCacheFiles".equals(method.getName())){
									method.invoke(pm, cache.getPackName(),new IPackageDataObserver.Stub() {
										@Override
										public void onRemoveCompleted(String packageName, boolean succeeded)
												throws RemoteException {
										}
									});
								}
							} catch (Exception e) {
								Intent intent = new Intent();
								intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
								intent.addCategory(Intent.CATEGORY_DEFAULT);
								intent.setData(Uri.parse("package:" + cache.getPackName()));
								startActivity(intent);
								e.printStackTrace();
							}
						}
					}
				});
				ll_cachecontainer.addView(view, 0);
				break;
			case MSG_FINISH:
				tv_clean_progress.setText("扫描结束");
//				tv_clean_progress.setText("共扫描到" + "项缓存信息，总大小");
				break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cleancache);
		
		pb_clean_progress = (ProgressBar) findViewById(R.id.pb_clean_progress);
		tv_clean_progress = (TextView) findViewById(R.id.tv_clean_progress);
		ll_cachecontainer = (LinearLayout) findViewById(R.id.ll_cachecontainer);
		
		pm = getPackageManager();
		
		new Thread(new Runnable(){
			@Override
			public void run() {
				List<PackageInfo> packInfos = pm.getInstalledPackages(0);
				pb_clean_progress.setMax(packInfos.size());
				int progress = 0;
				for (PackageInfo info : packInfos) {
					String packName = info.packageName;
					try {
						Method method = pm.getClass().getDeclaredMethod("getPackageSizeInfo", String.class, IPackageStatsObserver.class);
						method.invoke(pm, packName, new PkgSizeObserver());
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					Message msg = Message.obtain();
					msg.obj = info.applicationInfo.loadLabel(pm).toString();
					msg.what = MSG_SCANNING;
					handler.sendMessage(msg);
					progress++;
					pb_clean_progress.setProgress(progress);
				}
				
				handler.sendEmptyMessage(MSG_FINISH);
			}
		}).start();
	}
	
    private class PkgSizeObserver extends IPackageStatsObserver.Stub{  

		/** Call back. 
         * @param pStatus Return data in this object.  
         * @param succeeded If call back success return true. 
         */   
        @Override  
        public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)  
                throws RemoteException {
        	if(pStats.cacheSize > 0) {
	        	AppInfo app = new AppInfo();
	        	try {
	        		ApplicationInfo application = pm.getApplicationInfo(pStats.packageName, 0);
					app.setIcon(application.loadIcon(pm));
					app.setPackName(pStats.packageName);
					app.setName(application.loadLabel(pm).toString());
					app.setCachesize(pStats.cacheSize);
				} catch (Exception e) {
					e.printStackTrace();
				}
	        	Message msg = Message.obtain();
	        	msg.what = MSG_CACHE;
	        	msg.obj = app;
	        	handler.sendMessage(msg);
        	}
        }
    }
    
	public void cleanall(View v) {
		Method[] methods = PackageManager.class.getMethods();
		for(Method method:methods){
			if("freeStorageAndNotify".equals(method.getName())){
				try {
					method.invoke(pm, Integer.MAX_VALUE, new IPackageDataObserver.Stub() {
						@Override
						public void onRemoveCompleted(String packageName,
								boolean succeeded) throws RemoteException {
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
				return;
			}
		}
	}
}
